package com.lz.comm.image.progress

import android.os.SystemClock
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*

internal class ProgressResponseBody(
    private val url: String,
    private val respBody: ResponseBody,
    private val callback: ProgressCallback
) : ResponseBody() {

    private var bufferedSource: BufferedSource? = null

    override fun contentType(): MediaType? = respBody.contentType()

    override fun contentLength(): Long = respBody.contentLength()

    override fun source(): BufferedSource {
        if (null == bufferedSource) {
            bufferedSource = Okio.buffer(ProgressForwardingSource(respBody.source()))
        }
        return bufferedSource!!
    }

    inner class ProgressForwardingSource(delegate: Source) : ForwardingSource(delegate) {

        private var totalBytesRead = 0L

        private var lastModifyTime = 0L

        override fun read(sink: Buffer, byteCount: Long): Long {
            val bytesRead = super.read(sink, byteCount)
            totalBytesRead += if (bytesRead != -1L) bytesRead else 0
            val currentTime = SystemClock.elapsedRealtime()
            if (currentTime - lastModifyTime > Progressor.PROGRESS_INTERVAL_TIME) {
                lastModifyTime = currentTime
                callback.progress(url, totalBytesRead, respBody.contentLength())
            }
            return bytesRead
        }
    }
}